/**
 * 时间轴模块
 * 负责显示和管理用户的时间轴数据
 */

const { ipcRenderer } = require('electron');
const { showToast } = require('../../common/show-toast');


// 时间轴状态管理
let timelineState = {
    items: [], // 统一存储所有类型的数据
    statistics: {
        tasks: {
            total: 0,
            completed: 0,
            todayTotal: 0,
            todayCompleted: 0,
            weekTotal: 0,
            weekCompleted: 0,
            monthTotal: 0,
            monthCompleted: 0
        },
        pomodoros: {
            total: 0,
            todayCount: 0,
            todayMinutes: 0,
            weekCount: 0,
            weekMinutes: 0,
            monthCount: 0,
            monthMinutes: 0,
            averageMinutes: 0
        },
        countdowns: {
            total: 0,
            active: 0,
            completed: 0,
            nearestEvent: null
        }
    },
    filters: {
        currentTab: 'all',
        dateFilter: 'all',
        searchQuery: ''
    }
};
let isFirstLoad = true;//是否是第一次加载
// 自动刷新间隔（毫秒）
const AUTO_REFRESH_INTERVAL = 60000; // 1分钟

// 心得编辑相关变量
let currentEditingItemId = null;
function initialize() {
    if (isFirstLoad) {
        
        console.log('初始化时间轴...');
        initializeTimeline();//初始化时间轴
        updateStatistics();//更新统计信息
        setupEventListeners();//设置事件监听器
        timelineState.filters.currentTab = 'all';
        loadDataFromOtherModules();//从其他模块加载数据
        console.log('时间轴初始化完成');
        isFirstLoad = false;
    }else{
        console.log('时间轴已初始化，不再重复初始化');
        timelineState.filters.currentTab = 'all';
        loadDataFromOtherModules();//从其他模块加载数据
    }
}

//监听ipc消息
ipcRenderer.on('timeline', (event, data) => {
    console.info('收到来自主进程的消息:', data);
})


// 设置自动刷新
function setupAutoRefresh() {
    setInterval(() => {
        console.log('自动刷新时间轴数据...');
        loadDataFromOtherModules();
    }, AUTO_REFRESH_INTERVAL);
}

// 设置事件监听器
function setupEventListeners() {
    // 监听本地存储变化
    window.addEventListener('storage', (e) => {
        if (['calendarTasks', 'pomodoro_records', 'countdowns'].includes(e.key)) {
            console.log('检测到数据变化，刷新时间轴...');
            loadDataFromOtherModules();
        }
    });

    // 标签切换事件
    document.querySelectorAll('.timeline-tabs .tab').forEach(tab => {
        tab.addEventListener('click', (e) => {
            const tabName = e.target.dataset.tab;
            timelineState.filters.currentTab = tabName;
            updateActiveTab(tabName);
            updateTimelineContent();
        });
    });

    // 日期筛选事件
    document.querySelectorAll('.date-filters .date-filter').forEach(filter => {
        filter.addEventListener('click', (e) => {
            const filterName = e.target.dataset.filter;
            timelineState.filters.dateFilter = filterName;
            updateActiveDateFilter(filterName);
            updateTimelineContent();
        });
    });

    // 搜索框事件
    const searchInput = document.querySelector('.timeline-search input');
    if (searchInput) {
        searchInput.addEventListener('input', debounce((e) => {
            timelineState.filters.searchQuery = e.target.value.toLowerCase();
            updateTimelineContent();
        }, 300));
    }

    // 绑定心得按钮点击事件
    document.addEventListener('click', (e) => {
        const notesBtn = e.target.closest('.btn-notes');
        if (notesBtn) {
            const itemId = notesBtn.dataset.id;
            openNotesModal(itemId);
        }
    });

    // 绑定心得弹窗的按钮事件
    document.getElementById('cancel-notes')?.addEventListener('click', closeNotesModal);
    document.getElementById('save-notes')?.addEventListener('click', saveNotes);

    // 点击弹窗外部关闭
    window.addEventListener('click', (e) => {
        const modal = document.getElementById('notes-modal');
        if (e.target === modal) {
            closeNotesModal();
        }
    });
}

// 更新活动标签
function updateActiveTab(tabName) {
    document.querySelectorAll('.timeline-tabs .tab').forEach(tab => {
        tab.classList.toggle('active', tab.dataset.tab === tabName);
    });
}

// 更新活动日期筛选器
function updateActiveDateFilter(filterName) {
    document.querySelectorAll('.date-filters .date-filter').forEach(filter => {
        filter.classList.toggle('active', filter.dataset.filter === filterName);
    });
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 统一处理时间格式
function normalizeTimestamp(dateStr, timeStr) {
    if (!dateStr) return null;
    
    // 处理ISO格式的时间字符串 (2025-05-02T04:31:00.000Z)
    if (dateStr.includes('T')) {
        return new Date(dateStr).getTime();
    }
    
    // 处理日期和时间分开的情况
    const date = new Date(dateStr);
    if (timeStr) {
        const [hours, minutes] = timeStr.split(':').map(Number);
        date.setHours(hours || 0, minutes || 0, 0, 0);
    } else {
        date.setHours(0, 0, 0, 0);
    }
    return date.getTime();
}

// 从其他模块加载数据
function loadDataFromOtherModules() {
    try {
        timelineState.items = [];

        // 加载日历待办数据
        const calendarTasks = localStorage.getItem('calendarTasks');
        // console.log('calendarTasks', calendarTasks);
        if (calendarTasks) {
            const tasks = JSON.parse(calendarTasks);
            const formattedTasks = tasks.map(task => ({
                id: task.id || Date.now(),
                type: 'task',
                title: task.title || '待办事项',
                description: task.description || '',
                timestamp: normalizeTimestamp(task.end),
                notes: task.notes || '',
                status: task.completed ? '已完成' : '进行中',
                category: '日历待办',
                color: task.color || '#68a67d',
                priority: task.priority || 'normal',
                dueDate: task.start
            }));
            timelineState.items = timelineState.items.concat(formattedTasks);
        }

        // 加载番茄时钟数据
        const pomodoroRecords = localStorage.getItem('pomodoro_records');
        // console.log('pomodoroRecords', pomodoroRecords);
        if (pomodoroRecords) {
            const pomodoros = JSON.parse(pomodoroRecords);
            const formattedPomodoros = pomodoros.map(pomodoro => ({
                id: pomodoro.id || Date.now(),
                type: 'pomodoro',
                title: '专注时间',
                description: `完成了 ${pomodoro.duration || 25} 分钟的专注`,
                timestamp: normalizeTimestamp(pomodoro.timestamp),
                duration: pomodoro.duration || 25,
                notes: pomodoro.notes || '',
                dueDate: pomodoro.startTime || '',
                endTime: pomodoro.endTime || '',
                status: '已完成',
                category: '番茄时钟',
                color: '#F18F01',
                focusType: pomodoro.focusType || '工作'
            }));
            timelineState.items = timelineState.items.concat(formattedPomodoros);
        }

        // 加载倒计时数据
        const countdownEvents = localStorage.getItem('countdowns');
        // console.log('countdownEvents', countdownEvents);
        if (countdownEvents) {
            const countdowns = JSON.parse(countdownEvents);
            const formattedCountdowns = countdowns.map(countdown => {
                const timestamp = normalizeTimestamp(countdown.date, countdown.time || '00:00');
                return {
                    id: countdown.id || Date.now(),
                    type: 'countdown',
                    title: countdown.title || '倒计时事项',
                    description: `${countdown.category || '其他'} - ${formatDate(timestamp)}`,
                    timestamp: timestamp,
                    notes: countdown.notes || '',
                    status: isCountdownActive(timestamp) ? '进行中' : '已结束',
                    category: '未来倒计时',
                    color: '#3498db',
                    remainingTime: getRemainingTime(timestamp)
                };
            });
            timelineState.items = timelineState.items.concat(formattedCountdowns);
        }

        // 按时间戳排序
        timelineState.items.sort((a, b) => a.timestamp - b.timestamp);
        // console.log('timelineState.items', timelineState.items);
        //判断本地存储是否存在timelineState
        // 从本地存储加载时间轴状态
        if (localStorage.getItem('timelineState')) {
            const storedState = JSON.parse(localStorage.getItem('timelineState'));
            
            // 合并存储的items和新加载的items
            const mergedItems = [...timelineState.items];
            
            // 遍历存储的状态,根据ID更新或添加数据
            storedState.items.forEach(storedItem => {
                const existingIndex = mergedItems.findIndex(item => item.id === storedItem.id);
                if (existingIndex >= 0) {
                    // 如果已存在则保留最新数据
                    const existingItem = mergedItems[existingIndex];
                    if(storedItem.notes != '') {
                        mergedItems[existingIndex] = {
                            ...storedItem,
                            notes: storedItem.notes // 保留原有的notes
                        };
                    }
                } else {
                    // 如果不存在则添加
                    mergedItems.push(storedItem);
                }
            });

            // 更新timelineState
            timelineState = {
                ...timelineState,
                items: mergedItems,
                filters: storedState.filters || timelineState.filters
            };
        }
        
        // 保存最新状态到本地存储
        localStorage.setItem('timelineState', JSON.stringify(timelineState));
        // 更新统计信息
        updateDetailedStatistics();
        
        updateTimelineContent();
        console.info('时间轴数据加载完成:', timelineState);
    } catch (err) {
        console.error('加载时间轴数据失败:', err);
        showToast('加载时间轴数据失败', 'error');
    }
}

// 检查倒计时是否激活
function isCountdownActive(timestamp) {
    return timestamp > Date.now();
}

// 格式化日期
function formatDate(timestamp) {
    const date = new Date(timestamp);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 获取剩余时间
function getRemainingTime(timestamp) {
    const now = Date.now();
    const diff = timestamp - now;
    
    if (diff <= 0) return '已结束';
    
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    
    if (days > 0) return `${days}天${hours}小时`;
    if (hours > 0) return `${hours}小时${minutes}分钟`;
    return `${minutes}分钟`;
}

// 初始化时间轴
function initializeTimeline() {
    const timeline = document.getElementById('timeline');
    if (!timeline) return;

    // 添加标签切换
    const tabsHTML = `
        <div class="timeline-header">
            <div class="timeline-title">
                <h1>时间轴</h1>
                <p class="subtitle">记录你的时间轨迹</p>
            </div>
            <div class="timeline-filters">
                <div class="timeline-tabs">
                    <button class="tab active" data-tab="all">
                        <i class="fas fa-layer-group"></i>
                        全部
                    </button>
                    <button class="tab" data-tab="task">
                        <i class="fas fa-tasks"></i>
                        待办事项
                    </button>
                    <button class="tab" data-tab="pomodoro">
                        <i class="fas fa-clock"></i>
                        番茄时间
                    </button>
                    <button class="tab" data-tab="countdown">
                        <i class="fas fa-hourglass-half"></i>
                        倒计时
                    </button>
                </div>
                <div class="date-filters">
                    <button class="date-filter active" data-filter="today">
                        <i class="fas fa-calendar-day"></i>
                        今天
                    </button>
                    <button class="date-filter" data-filter="week">
                        <i class="fas fa-calendar-week"></i>
                        本周
                    </button>
                    <button class="date-filter" data-filter="month">
                        <i class="fas fa-calendar-alt"></i>
                        本月
                    </button>
                </div>
            </div>
        </div>
    `;

    // 添加统计面板
    const statsHTML = `
        <div class="timeline-stats">
            <div class="stats-header">今日统计</div>
            <div class="stats-grid">
                <div class="time-line-stats-card">
                    <div class="stats-title">
                        <i class="fas fa-stopwatch"></i>
                        专注时长
                    </div>
                    <div class="stats-progress">
                        <div class="progress-bar">
                            <div class="progress" style="width: 0%"></div>
                        </div>
                        <span class="progress-text">0分钟</span>
                    </div>
                </div>
                <div class="time-line-stats-card">
                    <div class="stats-title">
                        <i class="fas fa-check-circle"></i>
                        待办完成
                    </div>
                    <div class="stats-progress">
                        <div class="progress-bar">
                            <div class="progress" style="width: 0%"></div>
                        </div>
                        <span class="progress-text">0/0</span>
                    </div>
                </div>
                <div class="time-line-stats-card">
                    <div class="stats-title">
                        <i class="fas fa-tomato"></i>
                        番茄数
                    </div>
                    <div class="stats-progress">
                        <div class="progress-bar">
                            <div class="progress" style="width: 0%"></div>
                        </div>
                        <span class="progress-text">0个</span>
                    </div>
                </div>
            </div>
        </div>
    `;

    // 添加时间轴内容区
    const contentHTML = `
        <div class="timeline-content">
            <div class="timeline-items"></div>
        </div>
    `;

    // 添加心得编辑弹窗
    const notesModalHTML = `
        <div id="notes-modal" class="modal">
            <div class="modal-content notes-edit-content">
                <div class="modal-header">
                    <h3 id="notes-modal-title">添加心得</h3>
                </div>
                <div class="modal-body">
                    <textarea id="notes-content" placeholder="请输入你的心得..." rows="6"></textarea>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" id="cancel-notes">取消</button>
                    <button class="btn btn-primary" id="save-notes">确认</button>
                </div>
            </div>
        </div>
    `;



    timeline.innerHTML = tabsHTML + statsHTML + contentHTML + notesModalHTML;

    // 绑定事件
    bindTimelineEvents();
    // updateTimelineContent();
}

// 创建时间轴项目HTML
function createTimelineItemHTML(item, isFirst, isLast) {
    const time = new Date(item.timestamp).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
    });
    const endTime = new Date(item.dueDate).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
    });

    let statusClass = '';
    let statusIcon = '';
    let typeIcon = '';
    let typeClass = '';

    // 设置状态图标和类名
    switch (item.status) {
        case '已完成':
            statusIcon = '<i class="fas fa-check-circle" style="color: #4CAF50;"></i>';
            statusClass = 'completed';
            break;
        case '进行中':
            statusIcon = '<i class="fas fa-clock" style="color: #2196F3;"></i>';
            statusClass = 'in-progress';
            break;
        case '已结束':
            statusIcon = '<i class="fas fa-flag-checkered" style="color: #9E9E9E;"></i>';
            statusClass = 'ended';
            break;
    }

    // 设置类型图标和类名
    switch (item.type) {
        case 'task':
            typeIcon = '<i class="fas fa-tasks"></i>';
            typeClass = 'task-item';
            break;
        case 'pomodoro':
            typeIcon = '<i class="fas fa-clock"></i>';
            typeClass = 'pomodoro-item';
            break;
        case 'countdown':
            typeIcon = '<i class="fas fa-hourglass-half"></i>';
            typeClass = 'countdown-item';
            break;
    }

    return `
        <div class="timeline-item ${typeClass} ${statusClass}" data-id="${item.id}">
            <div class="timeline-time-column">
                <div class="timeline-time">${item.type === 'task' || item.type === 'pomodoro' ? endTime : time}</div>
                <div class="timeline-line${isFirst ? ' first' : ''}${isLast ? ' last' : ''}">
                    <div class="timeline-dot" style="background-color: ${item.color}"></div>
                </div>
                
                ${item.type === 'task' || item.type === 'pomodoro' ? `
                    <div class="timeline-time">${time}</div>
                ` : `
                    <div class="timeline-time" style="color: var(--bg-200)">${time}</div>
                `}
            </div>
            <div class="timeline-item-content">
                <div class="timeline-item-header">
                    <div class="timeline-item-title">
                        ${statusIcon}
                        <span>${item.title}</span>
                    </div>
                    <div class="timeline-item-type">
                        <span class="timeline-item-tag" style="background-color: ${item.color}20; color: ${item.color}">
                            ${typeIcon} ${item.category}
                        </span>
                    </div>
                </div>
                <div class="timeline-item-description">${item.description}</div>
                <div class="timeline-item-footer">
                    ${item.duration ? `
                        <span class="timeline-item-duration">
                            <i class="fas fa-hourglass-half"></i> ${formatDuration(item.duration)}
                        </span>
                    ` : ''}
                    ${item.type === 'countdown' ? `
                        <span class="timeline-item-countdown">
                            <i class="fas fa-clock"></i> ${item.remainingTime}
                        </span>
                    ` : `
                        <span class="timeline-item-countdown">
                            <i class="fas fa-clock"></i>${item.status && item.status === '已完成' ? '已完成' : ''} ${item.type === 'task' ? formatDate(item.dueDate) : formatDate(item.timestamp)}
                        </span>
                    `}
                    <div class="timeline-item-actions">
                        <button class="btn-notes" data-id="${item.id}" title="添加心得">
                            <i class="fas fa-edit"></i> 心得
                        </button>
                    </div>
                    ${item.notes ? `
                        
                    ` : ''}
                </div>
            </div>
        </div>
    `;
}

// 更新今日待办列表
// function updateTodayTasksList() {
//     const todayTasksList = document.querySelector('.today-tasks-list');
//     if (!todayTasksList) return;

//     const now = new Date();
//     const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
//     const endOfDay = startOfDay + 24 * 60 * 60 * 1000;

//     const todayTasks = timelineState.items.filter(item => 
//         item.type === 'task' && 
//         item.timestamp >= startOfDay && 
//         item.timestamp < endOfDay
//     ).sort((a, b) => a.timestamp - b.timestamp);

//     if (todayTasks.length === 0) {
//         todayTasksList.innerHTML = `
//             <div class="empty-tasks">
//                 <i class="fas fa-clipboard-list"></i>
//                 <p>今日暂无待办事项</p>
//             </div>
//         `;
//         return;
//     }

//     todayTasksList.innerHTML = todayTasks.map(task => `
//         <div class="task-item ${task.status === '已完成' ? 'completed' : ''}" data-id="${task.id}">
//             <div class="task-checkbox">
//                 ${task.status === '已完成' ? 
//                     '<i class="fas fa-check-circle"></i>' : 
//                     '<i class="far fa-circle"></i>'}
//             </div>
//             <div class="task-content">
//                 <div class="task-title">${task.title}</div>
//                 <div class="task-time">${new Date(task.timestamp).toLocaleTimeString('zh-CN', {
//                     hour: '2-digit',
//                     minute: '2-digit'
//                 })}</div>
//             </div>
//         </div>
//     `).join('');
// }

// 更新时间轴内容
function updateTimelineContent() {
    const itemsContainer = document.querySelector('.timeline-content');
    if (!itemsContainer) return;

    // 获取筛选条件
    const activeTab = timelineState.filters.currentTab;
    const activeFilter = timelineState.filters.dateFilter;
    const searchQuery = timelineState.filters.searchQuery.toLowerCase();

    // 获取筛选后的项目
    let items = getFilteredItems(activeFilter, activeTab);
    // console.log('updateTimelineContent', items);

    // 应用搜索过滤
    if (searchQuery) {
        items = items.filter(item => 
            item.title.toLowerCase().includes(searchQuery) ||
            item.description.toLowerCase().includes(searchQuery) ||
            item.notes.toLowerCase().includes(searchQuery)
        );
    }

    // 按时间戳排序
    items.sort((a, b) => a.timestamp - b.timestamp);

    if (items.length === 0) {
        itemsContainer.innerHTML = `
            <div class="timeline-empty">
                <i class="fas fa-calendar-times"></i>
                <p>暂无${getTabName(activeTab)}记录</p>
                <p class="empty-subtitle">
                    ${activeFilter !== 'all' ? '尝试切换其他时间范围' : '开始记录你的时间轨迹吧'}
                </p>
            </div>
        `;
        return;
    }

    // 按日期分组
    const groupedItems = groupItemsByDate(items);
    
    // 生成HTML
    const html = Object.entries(groupedItems).map(([date, dateItems]) => {
        const itemsHtml = dateItems.map((item, index) => 
            createTimelineItemHTML(
                item, 
                index === 0, 
                index === dateItems.length - 1
            )
        ).join('');

        return `
            <div class="timeline-date-group">
                <div class="timeline-date-header">
                    <i class="fas fa-calendar-day"></i>
                    ${formatDateHeader(date)}
                    <span class="item-count">${dateItems.length}项</span>
                </div>
                <div class="timeline-items">
                    ${itemsHtml}
                </div>
            </div>
        `;
    }).join('');

    itemsContainer.innerHTML = html;

    // 更新统计信息
    updateDetailedStatistics();
}

// 绑定时间轴事件
function bindTimelineEvents() {
    // 标签切换
    document.querySelectorAll('.timeline-tabs .tab').forEach(tab => {
        tab.addEventListener('click', (e) => {
            document.querySelectorAll('.timeline-tabs .tab').forEach(t => t.classList.remove('active'));
            e.target.classList.add('active');
            updateTimelineContent();
        });
    });

    // 日期筛选
    document.querySelectorAll('.date-filter').forEach(filter => {
        filter.addEventListener('click', (e) => {
            document.querySelectorAll('.date-filter').forEach(f => f.classList.remove('active'));
            e.target.closest('.date-filter').classList.add('active');
            updateTimelineContent();
        });
    });

    // 添加自动刷新
    // setInterval(() => {
    //     loadDataFromOtherModules();
    // }, 60000); // 每分钟刷新一次
}

// 格式化时长
function formatDuration(minutes) {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return hours > 0 ? `${hours}小时${mins}分钟` : `${mins}分钟`;
}

// 更新统计信息
function updateStatistics() {
    const now = new Date();
    const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
    const endOfDay = startOfDay + 24 * 60 * 60 * 1000;
    // 计算统计数据
    const stats = {
        todayTasks: 0,
        todayCompletedTasks: 0,
        todayPomodoroMinutes: 0,
        totalCountdowns: 0,
        completedCountdowns: 0
    };

    timelineState.items.forEach(item => {
        if (item.timestamp >= startOfDay && item.timestamp < endOfDay) {
            if (item.type === 'task') {
                stats.todayTasks++;
                if (item.status === '已完成') stats.todayCompletedTasks++;
            } else if (item.type === 'pomodoro') {
                stats.todayPomodoroMinutes += item.duration || 0;
            }
        }
        if (item.type === 'countdown') {
            stats.totalCountdowns++;
            if (item.status === '已结束') stats.completedCountdowns++;
        }
    });

    // 更新进度条
    const progressBars = document.querySelectorAll('.timeline-stats .progress');
    if (progressBars.length >= 3) {
        // 待办完成率
        const taskCompletionRate = stats.todayTasks > 0 ? (stats.todayCompletedTasks / stats.todayTasks * 100) : 0;
        progressBars[0].style.width = `${taskCompletionRate}%`;

        // 专注时长进度（假设目标是8小时）
        const pomodoroProgress = Math.min(stats.todayPomodoroMinutes / 480 * 100, 100);
        progressBars[1].style.width = `${pomodoroProgress}%`;

        // 倒计时完成率
        const countdownCompletionRate = stats.totalCountdowns > 0 ? (stats.completedCountdowns / stats.totalCountdowns * 100) : 0;
        progressBars[2].style.width = `${countdownCompletionRate}%`;
    }
}

// 获取筛选后的项目
function getFilteredItems(filter, tab) {
    const now = new Date();
    const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0).getTime();
    const startOfWeek = new Date(now.setDate(now.getDate() - now.getDay())).getTime();
    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1).getTime();

    return timelineState.items.filter(item => {
        // 类型筛选
        if (tab !== 'all' && item.type !== tab) return false;

        // 时间筛选
        switch (filter) {
            case 'today':
                return item.timestamp >= startOfDay;
            case 'week':
                return item.timestamp >= startOfWeek;
            case 'month':
                return item.timestamp >= startOfMonth;
            default:
                return true;
        }
    });
}

// 更新统计信息
function updateDetailedStatistics() {
    const now = new Date();
    const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
    const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
    // 计算本周开始时间 (周日为每周第一天)
    const startOfWeek = new Date(now);
    startOfWeek.setDate(now.getDate() - now.getDay());
    startOfWeek.setHours(0, 0, 0, 0);

    // 计算本周结束时间
    const endOfWeek = new Date(now); 
    endOfWeek.setDate(now.getDate() - now.getDay() + 6);
    endOfWeek.setHours(23, 59, 59, 999);
    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0);
    const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59);
    // 重置统计数据
    Object.keys(timelineState.statistics).forEach(key => {
        const stat = timelineState.statistics[key];
        Object.keys(stat).forEach(subKey => {
            stat[subKey] = 0;
        });
    });

    // 遍历所有项目进行统计
    timelineState.items.forEach(item => {
        const itemDate = new Date(item.timestamp);
        
        switch (item.type) {
            case 'task':
                updateTaskStatistics(item, itemDate, startOfToday, startOfWeek, startOfMonth, endOfDay, endOfWeek, endOfMonth);
                break;
            case 'pomodoro':
                updatePomodoroStatistics(item, itemDate, startOfToday, startOfWeek, startOfMonth, endOfDay, endOfWeek, endOfMonth);
                break;
            case 'countdown':
                updateCountdownStatistics(item, itemDate, startOfToday, startOfWeek, startOfMonth, endOfDay, endOfWeek, endOfMonth);
                break;
        }
    });

    // 计算平均值和百分比
    calculateAverages();
    
    // 更新显示
    updateStatisticsDisplay();
}

// 更新任务统计
function updateTaskStatistics(task, itemDate, startOfToday, startOfWeek, startOfMonth, endOfDay, endOfWeek, endOfMonth) {
    timelineState.statistics.tasks.total++;
    if (task.status === '已完成') timelineState.statistics.tasks.completed++;

    if (itemDate >= startOfToday && itemDate < endOfDay) {
        timelineState.statistics.tasks.todayTotal++;
        if (task.status === '已完成') timelineState.statistics.tasks.todayCompleted++;
    }
    if (itemDate >= startOfWeek && itemDate < endOfWeek) {
        timelineState.statistics.tasks.weekTotal++;
        if (task.status === '已完成') timelineState.statistics.tasks.weekCompleted++;
    }
    if (itemDate >= startOfMonth && itemDate < endOfMonth) {
        timelineState.statistics.tasks.monthTotal++;
        if (task.status === '已完成') timelineState.statistics.tasks.monthCompleted++;
    }
}

// 更新番茄时钟统计
function updatePomodoroStatistics(pomodoro, itemDate, startOfToday, startOfWeek, startOfMonth, endOfDay, endOfWeek, endOfMonth) {
    timelineState.statistics.pomodoros.total++;
    const duration = pomodoro.duration || 25;

    if (itemDate >= startOfToday && itemDate < endOfDay) {
        timelineState.statistics.pomodoros.todayCount++;
        timelineState.statistics.pomodoros.todayMinutes += duration;
    }
    if (itemDate >= startOfWeek && itemDate < endOfWeek) {
        timelineState.statistics.pomodoros.weekCount++;
        timelineState.statistics.pomodoros.weekMinutes += duration;
    }
    if (itemDate >= startOfMonth && itemDate < endOfMonth) {
        timelineState.statistics.pomodoros.monthCount++;
        timelineState.statistics.pomodoros.monthMinutes += duration;
    }
}

// 更新倒计时统计
function updateCountdownStatistics(countdown, itemDate, startOfToday, startOfWeek, startOfMonth, endOfDay, endOfWeek, endOfMonth) {
    timelineState.statistics.countdowns.total++;
    
    if (countdown.status === '进行中') {
        timelineState.statistics.countdowns.active++;
    } else {
        timelineState.statistics.countdowns.completed++;
    }

    // 更新最近的倒计时事件
    if (countdown.status === '进行中' && 
        (!timelineState.statistics.countdowns.nearestEvent ||
         itemDate < new Date(timelineState.statistics.countdowns.nearestEvent.timestamp))) {
        timelineState.statistics.countdowns.nearestEvent = countdown;
    }
}

// 计算平均值
function calculateAverages() {
    const stats = timelineState.statistics;
    
    // 计算番茄时钟平均时长
    if (stats.pomodoros.total > 0) {
        stats.pomodoros.averageMinutes = Math.round(
            (stats.pomodoros.monthMinutes / stats.pomodoros.monthCount) * 10
        ) / 10;
    }
}

// 更新统计显示
function updateStatisticsDisplay() {
    const stats = timelineState.statistics;
    const statsSection = document.querySelector('.timeline-stats');
    if (!statsSection) return;

    // 更新统计面板内容
    statsSection.innerHTML = `
        <div class="stats-section">
            <h3>数据统计</h3>
            <div class="stats-grid">
                <div class="stats-card">
                    <h4>待办事项</h4>
                    <div class="stats-item">
                        <span>今日完成率</span>
                        <div class="progress-bar">
                            <div class="progress" style="width: ${calculatePercentage(stats.tasks.todayCompleted, stats.tasks.todayTotal)}%"></div>
                        </div>
                        <span class="progress-text">${stats.tasks.todayCompleted}/${stats.tasks.todayTotal}</span>
                    </div>
                    <div class="stats-details">
                        <div>本周完成: ${stats.tasks.weekCompleted}/${stats.tasks.weekTotal}</div>
                        <div>本月完成: ${stats.tasks.monthCompleted}/${stats.tasks.monthTotal}</div>
                    </div>
                </div>
                
                <div class="stats-card">
                    <h4>番茄时钟</h4>
                    <div class="stats-item">
                        <span>今日专注</span>
                        <div class="progress-bar">
                            <div class="progress" style="width: ${Math.min(stats.pomodoros.todayMinutes / 480 * 100, 100)}%"></div>
                        </div>
                        <span class="progress-text">${formatDuration(stats.pomodoros.todayMinutes)}</span>
                    </div>
                    <div class="stats-details">
                        <div>本周专注: ${formatDuration(stats.pomodoros.weekMinutes)}</div>
                        <div>平均时长: ${formatDuration(stats.pomodoros.averageMinutes)}</div>
                    </div>
                </div>
                
                <div class="stats-card">
                    <h4>倒计时</h4>
                    <div class="stats-item">
                        <span>完成进度</span>
                        <div class="progress-bar">
                            <div class="progress" style="width: ${calculatePercentage(stats.countdowns.completed, stats.countdowns.total)}%"></div>
                        </div>
                        <span class="progress-text">${stats.countdowns.completed}/${stats.countdowns.total}</span>
                    </div>
                    <div class="stats-details">
                        <div>进行中: ${stats.countdowns.active}</div>
                        ${stats.countdowns.nearestEvent ? 
                            `<div>最近截止: ${formatDate(stats.countdowns.nearestEvent.timestamp)}</div>` : 
                            '<div>无进行中的倒计时</div>'}
                    </div>
                </div>
            </div>
        </div>
    `;
}

// 计算百分比
function calculatePercentage(completed, total) {
    if (total === 0) return 0;
    return Math.round((completed / total) * 100);
}

// 获取标签名称
function getTabName(tab) {
    const tabNames = {
        'all': '相关',
        'task': '待办事项',
        'pomodoro': '番茄时钟',
        'countdown': '倒计时'
    };
    return tabNames[tab] || '相关';
}

// 按日期分组
function groupItemsByDate(items) {
    const groups = {};
    items.forEach(item => {
        const date = new Date(item.timestamp).toLocaleDateString('zh-CN');
        if (!groups[date]) {
            groups[date] = [];
        }
        groups[date].push(item);
    });
    return groups;
}

// 格式化日期头部
function formatDateHeader(date) {
    const today = new Date().toLocaleDateString('zh-CN');
    const yesterday = new Date(Date.now() - 86400000).toLocaleDateString('zh-CN');
    const tomorrow = new Date(Date.now() + 86400000).toLocaleDateString('zh-CN');
    
    if (date === today) return '今天';
    if (date === yesterday) return '昨天';
    if (date === tomorrow) return '明天';
    return date;
}

// 打开心得编辑弹窗
function openNotesModal(itemId) {
    const modal = document.getElementById('notes-modal');
    const textarea = document.getElementById('notes-content');
    const titleElement = document.getElementById('notes-modal-title');
    
    // 查找对应的项目
    const item = timelineState.items.find(item => item.id === itemId);
    if (!item) return;
    
    // 设置标题
    titleElement.textContent = `编辑心得 - ${item.title}`;
    
    // 设置当前值
    textarea.value = item.notes || '';
    
    // 记录当前编辑的项目ID
    currentEditingItemId = itemId;
    
    // 显示弹窗
    modal.style.display = 'block';
}

// 关闭心得编辑弹窗
function closeNotesModal() {
    const modal = document.getElementById('notes-modal');
    modal.style.display = 'none';
    currentEditingItemId = null;
}

// 保存心得
function saveNotes() {
    if (!currentEditingItemId) return;
    
    const textarea = document.getElementById('notes-content');
    const notes = textarea.value.trim();
    
    // 更新项目的心得
    const itemIndex = timelineState.items.findIndex(item => item.id === currentEditingItemId);
    if (itemIndex !== -1) {
        timelineState.items[itemIndex].notes = notes;
        
        // 保存到本地存储
        localStorage.setItem('timelineState', JSON.stringify(timelineState));
        
        // 更新显示
        updateTimelineContent();
        
        // 显示成功提示
        showToast('心得保存成功', 'success');
    }
    
    // 关闭弹窗
    closeNotesModal();
} 

// 导出模块
module.exports = {
    initialize
};